/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package cn.com.recloud.bbs.util;

import cn.com.recloud.bbs.constant.BbsConstant;
import cn.com.recloud.core.constant.SysConstant;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author Herry Hong
 * @description 获取联系人信息工具
 * @date 2020-06-08
 */
@Component
@Slf4j
public class UserUtil {

    @Autowired
    private HttpServletRequest request;
    /**
     * 获取当前用户的联系人id
     *
     * @return
     */
    public String getUserId() {
        String userId = getUser("userId");
        return null != userId ? userId : SysConstant.DEFAULT_ID;
    }

    /**
     * 获取当前联系人的名称
     *
     * @return
     */
    public String getUserName() {
        String name = getUser("userCode");
        return null != name ? name : BbsConstant.PLATFORM_APP;
    }

    /**
     * 从请求头中获取用户信息
     *
     * @param key
     * @return
     */
    private String getUser(String key) {
        try {
            //判断从哪个平台发送的请求
            String platForm = request.getHeader("Platform");
            if (BbsConstant.PLATFORM_APP.equals(platForm)) {
                //从头中获取用户信息
                String userStr = request.getHeader("User");
                log.debug("-->getUser:"+userStr);
                if (StringUtils.isNoneBlank(userStr)) {
                    String userInfo = URLDecoder.decode(AESUtil.aesDecrypt(userStr), "utf-8");
                    log.debug("-->userInfo:"+userInfo);
                    JSONObject jsonObject = JSONUtil.parseObj(userInfo);
                    return jsonObject.getStr(key);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
